from traceback import print_exc

from ttzScrapyProject.constants.UrlConstant import CARD_INFO_LIST_URL, CARD_INFO_AND_PWD_URL
from ttzScrapyProject.dao.BaseDao import MysqlDao
from ttzScrapyProject.utils import HttpUtils, MumberUtils, WeChatUtils, DateUtils


class ViewCardInfo(MysqlDao):
    def __init__(self):
        super().__init__()
        self.cursor = self.getCursor()
        self.db = self.getDB()
        self.tableName = 'model'

    def getCardInfo(self,loginUserVo,userToken):
        # 获取所有的卡密信息 "Price":"0",
        # url = "http://webapicname.coo456.com/apiNew/userAward?token=73c516eb247e135f0f86a92b1d63a0d8&client=app&GoodsType=freeca&PageNumber=1"
        try:
            cardInfoUrl = f"{CARD_INFO_LIST_URL}{userToken}&client=app&GoodsType=freeca&PageNumber=1"
            cardInfoResponse = HttpUtils.get("获取账号卡密列表",cardInfoUrl)
            data = cardInfoResponse['Data']
            if MumberUtils.strToInt(data['TotalCount']) ==0:
                print(f"{loginUserVo.phone} 没有可提取卡密")

            cardInfo = data['List']
            if len(cardInfo) == 0:
                print(f"{loginUserVo.phone} 没有可提取卡密")
                return

            # 只获取未提取的卡密, Price 为 "0"
            idStr =""
            localCardList = []
            for card in cardInfo:
                if MumberUtils.strToInt(card["Price"]) != 0:
                    break
                localCardList.append(card)
                idStr = idStr + card["Id"] + ","

            idStr = idStr[0:len(idStr) - 1]
            # 查看火蚁卡卡密信息
            pwdUrl = f"{CARD_INFO_AND_PWD_URL}{userToken}&client=app&Ids={idStr}&FinancePwdAllow=1&Password=147852"
            pwdInfoResponse = HttpUtils.get("获取账号卡密信息",pwdUrl)
            pwdInfoList = pwdInfoResponse['Data']['Lists']
            if len(pwdInfoList) == 0:
                print(f"{loginUserVo.phone} 没有可提取卡密")
                return
            tempList = []
            for pwdInfo in pwdInfoList:
                cardNo = pwdInfo["CardNo"]
                cardSecret = pwdInfo["CardSecret"]
                for localCard in localCardList:
                    if localCard["OrderId"] == cardNo:
                        # 组装卡密信息
                        localCard["CardNoAndCardSecret"] = cardNo + "*" + cardSecret
                        selectSql = f"select * from scrapy_user_game.user_card_info i where i.USER_PHONE= %s and i.CARDNO_AND_CARDSECRET = %s"
                        selectValues = (loginUserVo.phone, localCard["CardNoAndCardSecret"])
                        self.cursor.execute(selectSql, selectValues)
                        result = self.cursor.fetchall()
                        if result:
                            pwdInfoList.remove(pwdInfo)
                            continue
                        insertSql  = f"INSERT INTO scrapy_user_game.user_card_info " \
                                     f"(USER_PHONE, CARD_NAME, CREATED_TIME, UPDATED_TIME, CARDNO_AND_CARDSECRET,STATUS)" \
                                     f"VALUES(%s, %s, %s, NULL, %s, %s)"
                        insertValues = (loginUserVo.phone,  localCard["Name"], DateUtils.timestamp2Date(MumberUtils.strToInt(localCard["CreateTime"])), localCard["CardNoAndCardSecret"],MumberUtils.strToInt("0"))
                        self.cursor.execute(insertSql, insertValues)
                        self.db.commit()
                        tempList.append(localCard)

            if len(tempList)>0:
                WeChatUtils.send_message(loginUserVo.userNoticeList,f"{loginUserVo.phone} 提取火蚁卡卡密成功,提取张数{len(tempList)}")
        except:
            print_exc()
            print(f"{loginUserVo.phone} 获取卡密信息异常")


if __name__ == '__main__':
    str1 = "12312,3123,"
    print(str1[0:len(str1)-1])
    list =[12,2132,3,23434,]
    print(list.index(2132))